<?php

namespace app\controllers;
use app\models\Menu;
use yii\db\Query;
use yii\web\Controller;


class RoleController extends AdminBaseController {
    //角色列表
    public function actionIndex(){
        $list=(new Query())->select('*')->from('yii_role')->orderBy('sort')->all();
        return $this->render('index',['list'=>$list]);
    }

    //添加角色
    public function actionAdd(){
        if ($this->post()){
         $data=\Yii::$app->request->post();
         $data['authority']=json_encode($data['authority']);
         $data['create_time']=time();
         $data['update_time']=time();
            if($this->check($data['name'])){
                return json_encode(['code'=>0,'msg'=>'角色已存在']);
            }
         $res=\Yii::$app->db->createCommand()->insert('yii_role',$data)->execute();
         if ($res){
             return json_encode(['code'=>1,'msg'=>'添加成功']);
         }else{
             return json_encode(['code'=>0,'msg'=>'添加失败']);
           }
         }
        $menu=$this->GetMenu();
        return $this->render('add',['menu'=>$menu]);
    }

    //编辑角色
    public function actionEdit(){
        if ($this->post()){
            $data=\Yii::$app->request->post();
            $data['authority']=json_encode($data['authority']);
            $data['update_time']=time();
            $res=\Yii::$app->db->createCommand()->update('yii_role',$data,array('id'=>$data['id']))->execute();
            if ($res){
                return json_encode(['code'=>1,'msg'=>'更新成功']);
            }else{
                return json_encode(['code'=>0,'msg'=>'更新失败']);
            }
        }
        $id=$this->GetId();
        $list=(new Query())->select('*')->from('yii_role')->where(array('id'=>$id))->one();
        $menu=$this->GetMenu();
        return $this->render('edit',['menu'=>$menu,'list'=>$list]);
    }

    //删除角色
    public function actionDel(){
        $id=$this->PostId();
        if ($this->checkadmin($id)){
            return json_encode(['code'=>0,'msg'=>'无法删除,该角色存在管理员']);
        }
        $res=\Yii::$app->db->createCommand()->delete('yii_role',array('id'=>$id))->execute();
        if ($res){
            return json_encode(['code'=>1,'msg'=>'删除成功']);
        }else{
            return json_encode(['code'=>0,'msg'=>'删除失败']);
        }
    }

    //获取一级菜单
    public function GetMenu(){
        $menu=Menu::find()->where(['parent_id'=>0])->orderBy('sort asc')->asArray()->all();
        return $menu;
    }

    //检查角色是否存在
    public function check($name){
        $check=(new Query())->from('yii_role')->where(array('name'=>$name))->exists();
        if ($check){
            return  true;
        }
    }

    //检查角色是否存在
    public function checkadmin($role_id){
        $check=(new Query())->from('yii_admin')->where(array('role_id'=>$role_id))->exists();
        if ($check){
            return  true;
        }else{
            return false;
        }
    }

}
